package com.wego.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.wego.bean.PageBean;
import com.wego.domain.entity.Strategy;
import com.wego.domain.query.StrategyQuery;
import com.wego.domain.vo.StrategyVO;
import com.wego.mapper.GameDataMapper;
import com.wego.mapper.StrategyMapper;
import com.wego.mapper.UserMapper;
import com.wego.service.StrategyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class StrategyServiceImpl implements StrategyService {
@Autowired
private StrategyMapper strategyMapper;
@Autowired
private UserMapper userMapper;
@Autowired
private GameDataMapper gameDataMapper;


    @Override
    public Strategy getById(Integer id) {
    //用户浏览量加1
        Strategy strategy = strategyMapper.selectByPrimaryKey(id);
        strategy.setViewCount(strategy.getViewCount() + 1);
        strategyMapper.updateByPrimaryKeySelective(strategy);
        return strategyMapper.selectByPrimaryKey(id);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteByIds(List<Integer> ids) {
        return strategyMapper.deleteByIds(ids);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, rollbackFor = Exception.class)
    public int batchInsert(List<Strategy> strategyList) {
        return strategyMapper.batchInsert(strategyList);
    }

    @Override
    public int update(Strategy strategy) {
        if (strategy == null) {
            throw new IllegalArgumentException("Strategy cannot be null");
        }
        if (strategy.getId() == null) {
            throw new IllegalArgumentException("ID cannot be null");
        }
        // 更新时也更新修改时间
        strategy.setUpdateTime(LocalDateTime.now());
        return strategyMapper.updateByPrimaryKeySelective(strategy);
    }

    @Override
    public Integer insert(Strategy strategy) {
        if (strategy == null) {
            throw new IllegalArgumentException("Strategy cannot be null");
        }
        if (strategy.getTitle() == null) {
            throw new IllegalArgumentException("Title cannot be null");
        }
        if (strategy.getContent() == null) {
            throw new IllegalArgumentException("Content cannot be null");
        }
        strategy.setState(0);
        // 设置创建时间和更新时间
        LocalDateTime now = LocalDateTime.now();
        strategy.setCreateTime(now);
        strategy.setUpdateTime(now);
        return strategyMapper.insertSelective(strategy);
    }

    @Override
    public String getAhurNameById(Integer id) {
        return userMapper.selectNicknameById(id);
    }

    @Override
    public String getGameNameById(Integer id) {
        return gameDataMapper.selectGameNameById(id);
    }

    /**
     * 获取带作者名和游戏名的分页数据
     * @param strategyQuery 查询条件
     * @return 带作者名和游戏名的分页数据
     */
    public PageBean<StrategyVO> getPageWithNames(StrategyQuery strategyQuery) {
        // 获取原始分页数据
        final Integer pageNum = strategyQuery.getPageNum();
        final Integer pageSize = strategyQuery.getPageSize();
        final Page<StrategyVO> page = PageHelper.startPage(pageNum, pageSize);
        List<StrategyVO> strategies = strategyMapper.selectAllNameWithCondition(strategyQuery);
        PageBean<StrategyVO> strategyPageBean = PageBean.page2pageBean(page);
        return strategyPageBean;
    }

    /**
     * 获取带作者名和游戏名的分页数据(旧方法，保留以保持向后兼容)
     * @param strategyQuery 查询条件
     * @return 带作者名和游戏名的分页数据
     */
    public PageBean<StrategyVO> getPageWithNamesOld(StrategyQuery strategyQuery) {
        // 获取原始分页数据
        final Integer pageNum = strategyQuery.getPageNum();
        final Integer pageSize = strategyQuery.getPageSize();
        final Page<Strategy> page = PageHelper.startPage(pageNum, pageSize);
        List<Strategy> strategies = strategyMapper.selectWithCondition(strategyQuery);
        PageBean<Strategy> strategyPageBean = PageBean.page2pageBean(page);

        // 转换为VO对象并补充作者名和游戏名
        PageBean<StrategyVO> voPageBean = new PageBean<>();
        voPageBean.setPageNum(strategyPageBean.getPageNum());
        voPageBean.setPageSize(strategyPageBean.getPageSize());
        voPageBean.setTotal(strategyPageBean.getTotal());

        List<StrategyVO> voList = strategyPageBean.getRecords().stream().map(strategy -> {
            StrategyVO vo = new StrategyVO();
            vo.setId(strategy.getId());
            vo.setTitle(strategy.getTitle());
            vo.setContent(strategy.getContent());
            vo.setViewCount(strategy.getViewCount());
            vo.setLikeCount(strategy.getLikeCount());
            vo.setState(strategy.getState());
            vo.setTextState(strategy.getTextState());
            vo.setAuthorId(strategy.getAuthorId());
            vo.setGameId(strategy.getGameId());
            if (strategy.getCreateTime() != null) {
                vo.setCreateTime(strategy.getCreateTime().toString());
            }

            // 补充作者名
            if (strategy.getAuthorId() != null) {
                String authorName = userMapper.selectNicknameById(strategy.getAuthorId());
                vo.setAuthorName(authorName);
            }

            // 补充游戏名
            if (strategy.getGameId() != null) {
                String gameName = gameDataMapper.selectGameNameById(strategy.getGameId());
                vo.setGameName(gameName);
            }

            return vo;
        }).toList();

        voPageBean.setRecords(voList);
        return voPageBean;
    }

    /**
     * 根据ID获取带作者名和游戏名的文章详情
     * @param id 文章ID
     * @return 带作者名和游戏名的文章详情
     */
    public StrategyVO getPageWithNamesById(Integer id) {
        List<StrategyVO> strategyVOS = strategyMapper.selectAllNameWithCondition(new StrategyQuery() {{
            setId(id);
        }});
        
        if (!strategyVOS.isEmpty()) {
            return strategyVOS.get(0);
        }
        
        return null;
    }
}
